//正则校验
var nameReg = /^[\u4e00-\u9fa5a-zA-Z0-9]{1,10}$/;
var areaReg = /^[\u4e00-\u9fa5]{1,10}$/;
var addressReg = /\S/;
var cellReg = /^1[34578]{1}\d{9}$/;
var areanoReg = /^[0-9]{3,4}$/;
var phoneReg = /^\d{7,8}$/;
var zipcodeReg = /^\d{6}$/;
var cellCodeReg = /^[A-Za-z0-9]{6}$/;
var moneyReg = /^(-)?(([1-9]{1}\d*)|([0]{1}))(\.(\d){1,2})?$/;
$(function () {
	//百度统计
	$("#settleSubmit").on("click", function(){
		_hmt.push(['_trackEvent', '提交订单PC', 'click', '提交订单PC']);
	});
	//返回顶部
	addGotop();
    //初始化地址列表
    getAddress();
    //选择地址-修改地址-删除地址
    $(".settle-receiver-address").on("click", "li", function () {
        $(this).addClass("selected").siblings().removeClass("selected");
        orderData.use_coin_for_ship_amount==1&&$("#settlePostToggle").click();
        queryExpressCharge();
    }).on("click", ".settle-address-edit", function (e) {
        var _this = this;
        $.dialog({
            title: "<p style='text-align:left'>编辑收货人信息</p>",
            html: $("#addressEditHtml").val(),
            btns: [{
                name: "保存收货人信息", ev: function (box) {
                    editAddress(editAddressUrl, $(_this).closest("li").attr("uid"), box);
                    return false;
                }
            }, {name: "取消编辑"}],
            init: function () {
                getUnitArea($(_this).closest("li").attr("uid"));
            }
        });
        e.stopPropagation();
    }).on("click", ".settle-address-del", function () {
        var li = $(this).closest("li");
        $.confirm("是否删除该地址？", function () {
            $.doAjax({
                url: delAddressUrl,
                data: {"uid": li.attr("uid")},
                success: function (data) {
                    li.remove();
					var size = $(".settle-receiver-address li").size();
                    size > 4 ? $(".settle-address-more").show() : $(".settle-address-more").hide();
					hasAddress(size>0)
                }
            });
        });
        return false;
    });
    //新增地址
    $(".settle-address-add").on("click", function () {
        $.dialog({
            title: "<p style='text-align:left'>添加收货人信息</p>",
            html: $("#addressEditHtml").val(),
            btns: [{
                name: "保存收货人信息", ev: function (box) {
                    addAddress(addAddressUrl, box);
                    return false;
                }
            }, {name: "取消添加"}],
            init: function () {
                getProvince();
            }
        });
    })

    //地址三级选择
    $(document).on("change", "#editProvince,#editCity", function (e, adata) {
            var uid = parseInt($(this).children("option:selected").val());
            if (!uid) {
                $(this).nextAll("select").html('<option value="">请选择</option>');
                return false;
            }
            var _this = this;
            var layer = $(this).is("#editProvince") ? 2 : 3;
            $.doAjax({
                url: areaUrl + uid + '&layer=' + layer,
                success: function (data) {
                    var html = '<option value="">请选择</option>';
                    $.each(data, function (i) {
                        html += '<option value="' + data[i].uid + '">' + data[i].name + '</option>';
                    });
                    $(_this).next().html(html).next().html('<option value="">请选择</option>');
                }
            });
        })
        //去除地址提示信息
        .on("focus", ".settle-address-edit-form input,.settle-address-edit-form select", function () {
            $(this).siblings(".error").hide();
        });

    //查看全部地址
    $(".settle-address-more").on("click", function () {
        var address = $(".settle-receiver-address");
        address.toggleClass("open");
        if (address.is(".open")) {
            $(this).children("i").text("收起").next().attr("class", "icon icon-arrow-up3");
        } else {
            $(this).children("i").text("更多地址").next().attr("class", "icon icon-arrow-down3");
        }
    });
    //复选框操作
    $(document).on({
        "click": function () {
            var o = $(this).children(".icon");
            if (o.is(".dis"))return false;
            o.is(".icon-stock-selected") ? o.attr("class", "icon icon-stock") : o.attr("class", "icon icon-stock-selected");
        }
    }, ".settle-edit-form-set-default, .settle-coupon-use, .settle-pay-balance-use, .settle-post-toggle");

    //获取验证码-手机校验
    $("#getCellCode").on("click", function () {
        if (!$(this).is(".dis")) {
            var cell = $("#checkCell").val();
            var error = $(this).siblings(".error");
            if (error.size() == 0) {
                var error = $('<span class="error"></span>')
                error.appendTo($(this).parent());
            } else {
                error.removeClass("ok");
            }
            if (!cell.match(cellReg)) {
                error.text("请输入正确的11位手机号码");
            } else {
                var _this = this;
                var text = $(this).text();
                error.text('');
                getCellCode(cell, function (data) {
                    error.text("短信发送成功").addClass("ok");
                    $(_this).addClass("dis").html('<i></i>秒后重新获取').next().removeClass("dis");
                    rTime($(_this).children("i").get(0), 60, function () {
                        $(_this).text('获取短信验证码').removeClass("dis");
                    });
                });
            }
        }
    });
    //校验手机验证码-手机校验
    $("#checkCellCode").on("click", function () {
        if (!$(this).is(".dis")) {
            var cell = $("#checkCell").val();
            var code = $("#cellCode").val();
            var error = $(this).siblings(".error");
            if (error.size() == 0) {
                var error = $('<span class="error"></span>')
                error.appendTo($(this).parent());
            } else {
                error.removeClass("ok");
            }
            if (!cell.match(cellReg)) {
                error.text("请输入正确的11位手机号码")
            } else if (!code.match(cellCodeReg)) {
                error.text("请输入正确短信验证码")
            } else {
                var _this = this;
                error.text('');
                checkCellCode(cell, code, function (data) {
                    error.text(data.msg)
                        .addClass("ok")
                        .siblings("input")
                        .prop("disabled", true);
                    $("#getCellCode").remove();
                    $("#checkCellCode").addClass("dis");
                    orderData.smsConfirm = code;
                });
            }
        }
    });
    //使用优惠券---暂时不做
    $(".settle-coupon-use").on("click", function () {
        var _this = this;
        setTimeout(function () {
            $(_this).children(".icon").hasClass("icon-stock-selected") ? $(".settle-coupon-info").show() : $(".settle-coupon-info").hide()
        }, 0);
    });
    //使用余额支付
    $(".settle-pay-balance-use").on("click", function () {
        var _this = this;
        setTimeout(function () {
			if($(_this).children(".icon").hasClass("icon-stock-selected")){
				$(".settle-balance-info").show();
			}else{
				$(".settle-balance-info").hide();
				orderData.member_money = null;
			}
        }, 0);
    });
    //输入金额-使用余额支付
    var settleBalanceAmount = $("#settleBalanceAmount").text() * 1;
    $("#settleBalanceUseAmount, #settleBalanceUseAmountUncheck").on("input", function () {
        var amount = $(this).val() * 1;
        var error = $(this).siblings(".error")
        if (!amount) {
            error.text("请输入正确的金额");
        } else if (amount > settleBalanceAmount) {
            error.text("金额超限");
        } else {
            error.text("");
        }
		orderData.member_money = amount;
    });
    //获取短信验证码-使用余额支付
    $("#getCellCodeSettleBalance").on("click", function () {
        if (!$(this).is(".dis")) {
            var _this = this;
            var amount = $("#settleBalanceUseAmount").val() * 1;
            var error = $(this).siblings(".error");
            if (amount > settleBalanceAmount || !amount) {
                return false;
            } else if (amount == '') {
                $("#settleBalanceUseAmount").next().text("请输入金额");
            } else {
                updateOrderData();
                orderData.member_money = amount;
                $.doAjax({
                    url: getCellCodeSettleBalanceUrl,
                    type: "post",
                    data: orderData,
                    success: function (data) {
                        if (data.flag) {
                            error.text("短信发送成功").addClass("ok");
                            $(_this).addClass("dis").html('<i></i>秒后重新获取').next().removeClass("dis");
                            rTime($(_this).children("i").get(0), 60, function () {
                                $(_this).text('获取短信验证码').removeClass("dis");
                            });
                        } else {
                            $.alert(data.msg);
                        }
                    }
                })
            }
        }
    });
    //校验短信验证码-使用余额支付
    $("#checkCellCodeSettleBalance").on("click", function () {
        var cellCode = $("#cellCodeSettleBalance").val();
        var error2 = $(this).siblings(".error");
        var error1 = $("#settleBalanceUseAmount").next(".error");
        if (!cellCode.match(cellCodeReg) || cellCode == '') {
            error2.text("短信验证码错误").removeClass("ok");
            return false;
        } else {
            updateOrderData();
            orderData.smsConfirm = cellCode;
            orderData.member_money = $("#settleBalanceUseAmount").val();
            $.doAjax({
                url: checkCellCodeSettleBalanceUrl,
                type: "post",
                data: orderData,
                success: function (data) {
                    if (data.flag) {
						console.log(data);
                        error1.text(data.msg).addClass("ok").prev().prop("disabled", true);
                        error2.parent().remove();
                        $("#useBalanceSelect").addClass("dis");
						$("#settleExpressCharge").text(data.ship_amount_discount);
						$("#reduceAmount").text(data.reduce_amount);
						$("#settleAmount").text(data.order_amount);
						$("#settleSdAmount").text(data.try_coin);
                    } else {
                        $.alert(data.msg);
                    }
                }
            });
        }
    });
    //用户手机号码未激活
    $("#settleBalanceUseConfirm").on("click", function () {
        if (!$(this).is(".dis")) {
            var balanceAmount = $("#settleBalanceAmount").text() * 1;
            var amount = $("#settleBalanceUseAmountUncheck").val();
            var error = $(this).siblings(".error");
            var _this = this;
            if (amount == "") {
                error.text("金额不能为空");
            } else if (amount <= balanceAmount) {
                updateOrderData();
                orderData.member_money = amount;

                $.doAjax({
                    url: checkCellCodeSettleBalanceUrl,
                    type: "post",
                    data: orderData,
                    success: function (data) {
                        if (data.flag) {
                            $("#settleBalanceUseAmountUncheck").prop("disabled", true);
                            $(_this).addClass("dis");
                            error.text(data.msg).addClass("ok");
                        } else {
                            error.text(data.msg);
                        }
                    }
                });
            }
        }
    })
    //校验试豆数量
    $("#settlePostToggle").on("click", function () {
		if(1*orderData.ship_amount_discount==0)return false;
        if ($("#isUseCoin").is(".icon-stock")) {
            var error = $(this).siblings(".error");
            updateOrderData();
            if (orderData.member_address_id) {
                orderData.use_coin_for_ship_amount = 1;
                $.doAjax({
                    url: checkSdAmount,
                    type: "post",
                    data: orderData,
                    success: function (data) {
                        var coinMsg = data.msg.ship_amount_try_coin;
                        if (coinMsg) {
                            error.text(coinMsg[0]);
                            $("#isUseCoin").attr("class", "icon icon-stock");
                        } else {
                            error.text('');
                            $("#settleExpressCharge").text("0.00");
                            $("#settleAmount").text(data.order_amount);
                            $("#settleSdAmount").text(data.try_coin);
                        }
                    }
                });
            } else {
                error.text("请选择一个收货人地址");
                return false;
            }
        } else {
            $("#settleExpressCharge").text($("#expressCharge").text());
            $("#settleAmount").text(orderData.order_amount);
            $("#settleSdAmount").text(orderData.try_coin);
			orderData.use_coin_for_ship_amount = 0;
        }
    })
    //提交结算
    $("#settleSubmit").on("click", function () {
        updateOrderData();
        $.doAjax({
            url: settleOrderUrl,
            type: "post",
            data: orderData,
            success: function (data) {
                if (data.flag) {
                    var url = data.payed ? settleSuccessUrlPayed : settleSuccessUrl;
                    window.location.href = url + data.order_info_id;
                } else {
                    for (var msg in data.msg) {
                        $.alert(data.msg[msg][0]);
                        break;
                    }
                }
            }
        });
    });
})
//读取省份数据
function getProvince(callback) {
    $.doAjax({
        url: areaUrl + '1&layer=1',
        success: function (data) {
            var html = '<option value="">请选择</option>';
            $.each(data, function (i) {
                html += '<option value="' + data[i].uid + '">' + data[i].name + '</option>';
            });
            $("#editProvince").html(html);
            $.isFunction(callback) && callback();
        }
    });
}
//读取全部地址数据
function getAddress() {
    $.doAjax({
        url: getAddressList,
        success: function (data) {
            data.data.length>0&&$(".settle-receiver-address").html(createAddressHtml(data.data));
			data.data.length >4?$(".settle-address-more").show():$(".settle-address-more").hide();
			hasAddress(data.data.length>0)
        }
    });
}
//生成地址html
function createAddressHtml(d) {
    var html = '';
    $.isArray(d) || (d = [d]);
    $.each(d, function (i) {
        var di = d[i];
        html += '<li express-charge="' + di.express_charge + '" uid="' + di.uid + '" class="' + (di.is_default == 1 ? "selected" : "") + '"><strong>' + di.consignee + '</strong>收<br>' + di.s1 + di.s2 + di.s3 + '<br>' + di.address + '<br>' + di.cell + '<span class="icon icon-addr-selected"></span><div class="settle-address-do"><span class="settle-address-edit">修改</span><span class="settle-address-del">删除</span></div></li>';
    });
    return html;
}
//新增地址
function addAddress(url, box) {
    var result = checkAddressForm("#settleAddressForm");
    if (result.isComplete) {
        $.doAjax({
            url: url,
            type: "post",
            data: result.data,
            success: function (data) {
                if (data.data) {
                    $(".settle-receiver-address").prepend(createAddressHtml(data.data)).children("li:eq(0)").click();
                    $(".settle-receiver-address li").size() > 4 ? $(".settle-address-more").show() : $(".settle-address-more").hide();
					hasAddress(true);
                    box.hideBox();
                } else {
                    $.alert(data.msg);
                }
				
            }
        });
    }
}
//修改地址
function editAddress(url, uid, box) {
    var result = checkAddressForm("#settleAddressForm");
    result.data.uid = uid;
    if (result.isComplete) {
        $.doAjax({
            url: url,
            type: "post",
            data: result.data,
            success: function (data) {
                if (data.data) {
                    var html = createAddressHtml(data.data);
                    var lastLi = $(".settle-receiver-address").children("li[uid='" + uid + "']");
                    if (data.data.is_default * 1 == 1) {
                        $(".settle-receiver-address").prepend(html);
                        lastLi.remove();
                    } else {
                        lastLi.after(html).remove();
                    }
                    $(".settle-receiver-address").children("li[uid='" + uid + "']").click();
                    box.hideBox();
                } else {
                    $.alert("请检查填写内容");
                }
            }
        });
    }
}
//验证地址表单数据
function checkAddressForm(form) {
    var REGs = {
        "consignee": nameReg,
        "address": addressReg,
        "cell": cellReg,
        "tel1": areanoReg,
        "tel2": phoneReg,
        "zipcode": zipcodeReg
    };
    var requireTips = {
        "consignee": "您未填写收货人！",
        "address": "详细地址不能为空！",
        "s1_uid": "请选择收货地址!",
        "s2_uid": "请选择收货地址!",
        "s3_uid": "请选择收货地址!",
        "cell": "手机号不能为空！"
    };
    var REGtips = {
        "consignee": "收货人名称限制为中英文",
        "address": "详细地址限制为中英文加数字，请规范格式！",
        "cell": "请正确输入11位手机号",
        "tel1": "请填写正确的区号",
        "tel2": "请填写正确的电话号码",
        "zipcode": "请填写正确的邮编"
    };
    var areaData = {};
    var isComplete = true;
    $(form).find("input,select").each(function () {
        var required = $(this).attr("required");
        var val = $(this).val();
        var name = $(this).attr("name");
        var error = $(this).siblings(".error");
        if (required && val == "") {
            isComplete && (isComplete = false);
            error.is(":hidden") && error.text(requireTips[name]).show();
        } else if (val != "" && !val.match(REGs[name])) {
            isComplete && (isComplete = false);
            error.is(":hidden") && error.text(REGtips[name]).show();
        } else {
            areaData[name] = val;
        }
    });
    areaData.is_default = $(".settle-edit-form-set-default .icon").hasClass("icon-stock-selected") ? 1 : 0;
    return {isComplete: isComplete, data: areaData};
}
//获取单个地址数据并填充表单
function getUnitArea(uid) {
    $.doAjax({
        url: getAddressUnit + uid,
        success: function (data) {
            if (data != "") {
                var formItem = ["consignee", "s1_uid", "s2_uid", "s3_uid", "address", "cell", "tel1", "tel2", "zipcode"];
                $.each(formItem, function (i) {
                    var dom = $("[name='" + formItem[i] + "']");
                    dom.size() > 0 && dom.get(0).tagName == "SELECT" ? dom.html(data[formItem[i].substring(0, 2)]) : dom.val(data[formItem[i]]);
                })
                data.is_default && $(".settle-edit-form-set-default .icon").attr("class", "icon icon-stock-selected");
            }
        }
    });
}
//获取手机验证码
function getCellCode(cell, callback) {
    if (cell.match(cellReg)) {
        $.doAjax({
            url: getCellCodeUrl,
			data: {"cell": cell},
            success: function (data) {
                if (data.flag) {
                    $.isFunction(callback) && callback(data)
                } else {
                    $.alert(data.msg);
                }
            }
        });
    }
}
//校验手机验证码
function checkCellCode(cell, cellCode, callback) {
    if (cell.match(cellReg) && cellCode.match(cellCodeReg)) {
        $.doAjax({
            url: checkCellCodeUrl,
			data: {"cell": cell, "cellCode": cellCode},
            success: function (data) {
                if (data.flag) {
                    $.isFunction(callback) && callback(data)
                } else {
                    $.alert(data.msg);
                }
            }
        });
    }
}
//获取当前结算页数据
function updateOrderData() {
    orderData.cell = $("#cellSettleBalance").text();
    orderData.member_address_id = $(".settle-receiver-address li.selected").attr("uid") || 0;
    orderData.use_coin_for_ship_amount = $("#isUseCoin").hasClass("icon-stock-selected") ? 1 : 0;
}
//查询快递费用
function queryExpressCharge() {
    updateOrderData();
    $.doAjax({
        url: checkSdAmount,
        type: "post",
        data: orderData,
        success: function (data) {
            if (data.flag) {
				var sad = data.ship_amount_discount;
				$("#expressCharge").text(sad);
				$("#settleExpressCharge").text(sad);
				$("#settleAmount").text(data.order_amount);
				$("#settleSdAmount").text(data.try_coin);
				$("#settleSdAmountDeduct").text(sad * 100);
				orderData.order_amount = data.order_amount;
				orderData.ship_amount_discount = sad;
            }
        }
    });
}
//是否有地址显示没有地址文案
function hasAddress(has){
	has?$("#settleAddress").show().siblings("#settleNoAddress").hide():$("#settleAddress").hide().siblings("#settleNoAddress").show();
}
